using System.Threading.Tasks;
using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Admin.NET.Application.Service;

/// <summary>
/// 常用指令服务
/// </summary>
[ApiDescriptionSettings(new string[] { "业务应用" }, Order = 100)]
public class CommonInstructService : IDynamicApiController, ITransient, IPrivateDependency
{
	private readonly SqlSugarRepository<CommonInstruct> _rep;

	private readonly UserManager _userManager;

	public CommonInstructService(SqlSugarRepository<CommonInstruct> rep, UserManager userManager)
	{
		_rep = rep;
		_userManager = userManager;
	}

	/// <summary>
	/// 获取常用指令列表
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpGet("/commoninstruct/page")]
	public async Task<dynamic> Page([FromQuery] CommonInstructInput input)
	{
		ISugarQueryable<CommonInstruct> query = (from u in _rep.Context.Queryable<CommonInstruct>()
			where u.CreateUserId == (long?)_userManager.UserId
			select u).WhereIF(!string.IsNullOrWhiteSpace(input.Name), (CommonInstruct u) => u.Name.Contains(input.Name.Trim()));
		ISugarQueryable<CommonInstruct> info = query.OrderBuilder(input);
		return await info.ToPagedListAsync(input.Page, input.PageSize);
	}

	/// <summary>
	/// 添加指令
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/commoninstruct/add")]
	public async Task AddInstruct([FromBody] AddCommonInstructInput input)
	{
		if (await _rep.IsAnyAsync((CommonInstruct u) => u.Name == input.Name.Trim() && u.CreateUserId == (long?)_userManager.UserId))
		{
			throw Oops.Bah("已添加同名指令，请更换名称");
		}
		CommonInstruct instruct = await _rep.GetFirstAsync((CommonInstruct u) => u.CreateUserId == (long?)_userManager.UserId && u.Instruct == input.Instruct.Trim());
		if (instruct != null)
		{
			throw Oops.Bah("该指令已添加，名称为：" + instruct.Name);
		}
		CommonInstruct data = input.Adapt<CommonInstruct>();
		await _rep.InsertAsync(data);
	}

	/// <summary>
	/// 删除指令
	/// </summary>
	/// <param name="input"></param>
	/// <returns></returns>
	[HttpPost("/commoninstruct/del")]
	public async Task DelInstruct([FromBody] DeleteCommonInstructInput input)
	{
		CommonInstruct data = await _rep.GetFirstAsync((CommonInstruct u) => u.Id == input.Id && u.CreateUserId == (long?)_userManager.UserId);
		if (data == null)
		{
			throw Oops.Bah("该指令不存在或已被删除");
		}
		await _rep.DeleteAsync(data);
	}
}
